const log = require('../com/logConfig.js')
const studentService = require('./studentService.js')
const logsService = require('./logsService.js')
const Model = require('../dbs/model/getCollection.js')
const TravelRecordSchema = require('../dbs/schema/travelRecordSchema.js')
const SecurityPointSchema = require('../dbs/schema/securityPointSchema.js')
const util = require('../com/util.js');

let sendQueue = {};

/**
 * 消费rabbitMq中的各种队列信息
 * @param {*} connection 
 */
let handleMessage = (connection) => {
    //监听学生位置队列
    connection.createChannel(function (error1, channel) {
        if (error1) {
            log.error("rabbitmq创建监听学生位置队列失败：", e);
        }
        let queue = global.COM_CONFIG.rabbitmq.queue;
        channel.assertQueue(queue, {
            durable: true
        });
        channel.consume(queue, function (msg) {
            // console.log("位置" + msg.content.toString());
            try {
                studentService.locationSave(msg.content.toString());
            } catch (e) { log.error(e) }
        }, {
            //消费了就从队列中删除这个消息
            noAck: true
        });
    });

    //消费出行记录队列信息
    connection.createChannel(function (error1, channel) {
        if (error1) {
            log.error("rabbitmq创建消费出行记录队列失败：", e);
        }
        let queue = global.COM_CONFIG.rabbitmq.travelRecordQueue;
        channel.assertQueue(queue, {
            durable: true
        });
        channel.consume(queue, function (msg) {
            // console.log("出行记录"+msg.content.toString());
            try {
                saveTravelRecord(msg.content.toString())
            } catch (e) { log.error(e) }
        }, {
            //消费了就从队列中删除这个消息
            noAck: true
        });
    });

    //消费保安位置队列  
    connection.createChannel(function (error1, channel) {
        if (error1) {
            log.error("rabbitmq消费保安位置创建队列失败：", e);
        }
        let queue = global.COM_CONFIG.rabbitmq.securityPointInfo;
        channel.assertQueue(queue, {
            durable: true
        });
        channel.consume(queue, function (msg) {
            // console.log("保安位置队列");
            // console.log(msg.content.toString())
            try {
                saveSecurityPoint(msg.content.toString())
            } catch (e) { log.error(e) }
        }, {
            //消费了就从队列中删除这个消息
            noAck: true
        });
    });

    //消费日志队列  
    connection.createChannel(function (error1, channel) {
        if (error1) {
            log.error("rabbitmq消费日志队列失败：", e);
        }
        let queue = global.COM_CONFIG.rabbitmq.quLogs;
        channel.assertQueue(queue, {
            durable: true
        });
        channel.consume(queue, function (msg) {
            //console.log("日志队列信息");
            // console.log(msg.content.toString())
            try {
                logsService.logSave(msg.content.toString());
            } catch (e) { log.error(e) }
        }, {
            //消费了就从队列中删除这个消息
            noAck: true
        });
    });


}

/**
 * 存保安位置记录数据
 * @param {*} data 
 */
let saveSecurityPoint = async (data) => {
    data = JSON.parse(data);
    data.data = JSON.parse(data.data)
    let SecurityPointModel = await Model.getComModel({
        dataBase: 'com_info',
        tableName: 'security_point',
        schema: SecurityPointSchema
    });
    //插入数据
    new SecurityPointModel(data).save();
    //handleSecurity(data);
}

/**
 * 处理保安看是否有收到学生报警任务
 * @param {*} data 
 */
let handleSecurity = async (data) => {
    if (!data.phone) { return; }
    global.COM_CONFIG.redis.hkeys('sos_handle', (err, doc) => {
        let filed = "sosSecurity_" + data.phone;
        for (let key in doc) {
            if (doc[key].indexOf(filed) != -1) {
                global.COM_CONFIG.redis.hget('sos_handle', doc[key], (er2, studentInfo) => {
                    studentInfo = JSON.parse(studentInfo);
                    let chartType=studentInfo.chartType;
                    let lon, lat;
                    if(chartType=='sos-security'){
                        let stuGps = studentInfo.gps;
                        for (let g in stuGps) {
                            if (stuGps[g].Latitude) {
                                lon = stuGps[g].Longitude;
                                lat = stuGps[g].Latitude;
                                break;
                            }
                        }
                    }else if(chartType=='sos-security'){
                        lon=studentInfo.alarmInfo.longitude;
                        lat=studentInfo.alarmInfo.latitude;
                    }
                    
                    if (lon && lat) {
                        let dis = util._getDisance(lat, lon, data.data.location.latitude, data.data.location.longitude);
                        if (dis <= global.COM_CONFIG.securityArrival) {
                            global.COM_CONFIG.post({
                                url: global.COM_CONFIG.activitiService.securityArrival,
                                data: JSON.stringify({
                                    secuId: data.phone,
                                    instanceId: studentInfo.instanceId,
                                    name: data.data.user.username,
                                    peopleType: 'CODE_SECURITY',
                                    taskType: studentInfo.taskType
                                })
                            });
                        }
                    }
                });
                break;
            }
        }
    });
}

/**
 * 存出行记录数据
 * @param {*} data 
 */
let saveTravelRecord = async (data) => {
    let TravekRecordModel = await Model.getComModel({
        dataBase: 'com_info',
        tableName: 'travel_record',
        schema: TravelRecordSchema
    });
    // 保存数据
    new TravekRecordModel(JSON.parse(data)).save();
}


/**
 * 组装消息提供者队列 - 暂时不需要node写消息进队列，所以就注释了
 */
let writeSendQueue = async (connection) => {
    //创建node-activiti队列的提供者
    // connection.createChannel(function (error1, channel) {
    //     if (error1) {
    //         log.error("rabbitmq创建消息提供者信道失败：", e);
    //     }
    //     var queue = global.COM_CONFIG.rabbitmq.nodeActivit;
    //     channel.assertQueue(queue, {
    //         // 队列持久化
    //         durable: true
    //     });
    //     //把连接存进去
    //     sendQueue[queue] = channel;
    //     //channel.sendToQueue(queue, Buffer.from(msg));
    // });
}

/**
 * 发送消息到node-activiti队列中
 * @param {*} msg 
 */
let sendToNodeActivitiQueue = async (msg) => {
    // sendQueue[global.COM_CONFIG.rabbitmq.nodeActivit].sendToQueue(global.COM_CONFIG.rabbitmq.nodeActivit, Buffer.from(msg),{
    //     // 消息持久化
    //     persistent: true        
    // });
}

module.exports = {
    handleMessage,
    writeSendQueue,
    sendToNodeActivitiQueue,
}